<template>
  <div class="contentwarp">
    <!-- <div v-show="showMap" class="toolsbar">
      <el-row>
        <el-col :span="24">
          <el-input placeholder="请输入地址" v-model="address" style="width:300px;"></el-input>
          <el-select v-model="cityValue" placeholder="请选择">
            <el-option v-for="item in citys" :key="item.value" :value="item.value">
            </el-option>
          </el-select>
          <el-button icon="el-icon-search" @click="searchAddress"></el-button>
        </el-col>
      </el-row>
    </div> -->
    <div v-show="showMap" id="qqmap">

    </div>
    <div v-show="showMap" class="peopleInfo">
      <ul class="infoList">
        <li class="item" v-for='(item,index) in deviceData'>
          <el-tooltip class="item" effect="dark" :content="item.address" placement="top-start">
            <span class="address" v-text='item.address'></span>
          </el-tooltip>
          <span class="updated_at" v-text='item.updated_at'></span>
        </li>
      </ul>
      <ul class="infoList">
        <li class="item" v-for='(item,index) in keyPersonData'>
          <span class="wxNum" v-text='item.wxNum'></span>
          <span class="updated_at">
            <el-button @click='trajectory(item)' style="padding:4px 7px" type="success">轨迹</el-button>
          </span>
        </li>
      </ul>
    </div>
    <div v-show="!showMap" class="contentwarp">
      <el-row class="tableToolsbar">
        <el-col :span="24">
          <el-input placeholder="请输入内容" style="width:200px;" class="input">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <el-button type="primary" @click='dialogAddTast=true'>增加任务</el-button>
          <el-dialog title="增加任务" :visible.sync="dialogAddTast" width="70%" :append-to-body='true'>
            <div>
              任务名称：<el-input style="width:200px;" v-model="input_task" placeholder="请输入内容"></el-input>
              备注：<el-input style="width:200px;" v-model="input_desc" placeholder="请输入内容"></el-input>
            </div>
            <div class="dialogAddTast">
              <div class="left">
                <div class="device">
                  <p class="label">选择设备</p>
                  <el-table :stripe="true" :data="deviceData" max-height='300' :border="true" style="width: 100%">
                    <el-table-column prop="address" label="地址"></el-table-column>
                    <el-table-column label="操作" width='100'>
                      <template slot-scope="scope">
                        <el-button @click="deviceChoose(scope.row)" size="mini">选中</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div class="keyPerson">
                  <p class="label">选择重点人</p>
                  <el-table :stripe="true" :data="keyPersonData" max-height='300' :border="true" style="width: 100%">
                    <el-table-column prop="wxNum" label="微信号"></el-table-column>
                    <el-table-column label="操作" width='100'>
                      <template slot-scope="scope">
                        <el-button @click="keyPersonChoose(scope.row)" size="mini">选中</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <div class="right">
                <div class="device">
                  <p class="label">已选择控点设备</p>
                  <el-tag v-for="tag in deviceTags" :key="tag.address" closable type="success">
                    {{tag.address}}
                  </el-tag>
                </div>
                <div class="keyPerson">
                  <p class="label">选择重点人</p>
                  <el-tag v-for="tag in keyPersonTags" :key="tag.wxNum" closable type="success">
                    {{tag.wxNum}}
                  </el-tag>
                </div>
              </div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogAddTast = false">取 消</el-button>
              <el-button type="primary" @click="dialogAddTast = false">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <el-table :stripe="true" :data="deviceData" :border="true" style="width: 100%">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="name" label="任务名称" width="100"></el-table-column>
        <el-table-column prop="updated_at" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="desc" label="设备备注"></el-table-column>
        <el-table-column prop="name" label="预警状态" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status==2" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="taskInfo(scope.$index,scope.row.latitude,scope.row.longitude)">查看</el-button>
            <el-button v-show="false" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button v-show="false" :disabled="scope.row.status == 0" size="mini" @click="handleEdit(scope.$index, scope.row)">数据</el-button>
            <el-button v-show="false" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="changeData" :page-size="dataSize" layout="total, prev, pager, next" :total="dataTotal"></el-pagination>
    </div>
  </div>
</template>

<script>
  import { TMap } from '../../utils/tmap'
  import { mapGetters } from 'vuex'

  export default {
    data() {
      return {
        dataTotal: 0,
        currentPage: 1,
        dataSize: 10,
        deviceData: [],
        deviceTags: [

        ],
        keyPersonTags: [

        ],
        keyPersonData: [{ wxNum: 15532916223 }, { wxNum: 15532913563 }, { wxNum: 15875316223 }, { wxNum: 15512486223 }, { wxNum: 13636786223 }],
        showMap: false, // 地图/列表切换控制
        map: null, // 地图资源
        qq: null,
        markersArray: [], // 地图标记
        currentIndex: 0, // 当前操作的数据索引
        address: '', // 搜索地址
        searchService: null, // pio检索
        customZoomControl: null, // 地图关闭div
        cityValue: '请选择',
        citys: [{ value: '儋州市' }, { value: '北京' }, { value: '上海' }, { value: '天津' }],
        geocoder: null,// 地址解析
        dialogAddTast: false,
        input_task: '',
        input_desc:'',
        circles: [],
        markers: [],
        labels: [],
        polylines: [],
      }
    },
    computed: {
      ...mapGetters([
        'GetQQMapKey'
      ])
    },
    methods: {
      headerCellStyle: function () {
        return 'background-color:#eeeeee'
      },
      loadData: function (page) {
        let that = this
        this.$axios.get(this.APIURL + '/device', { params: { page: page } }).then(function (data) {
          if (data !== false) {
            that.deviceData = data.data
            that.dataTotal = data.total
          }
        })
      },
      deviceChoose(row) {
        if (this.deviceTags.indexOf(row) == -1) {
          this.deviceTags.push(row)
        } else {
          this.$message({
            message: '设备已经被选择',
            type: 'warning'
          });
        }
      },
      keyPersonChoose(row) {
        if (this.keyPersonTags.indexOf(row) == -1) {
          this.keyPersonTags.push(row)
        } else {
          this.$message({
            message: '重点人已经被选择',
            type: 'warning'
          });
        }
      },
      trajectory(item) {
        this.clearOverlays(this.polylines)
        let trailData = [];
        let that = this;
        console.log(this.deviceData)
        for (let i of this.deviceData) {
          trailData.push(new qq.maps.LatLng(i.latitude, i.longitude))
        };
        let polyline = new qq.maps.Polyline({
          path: trailData,
          strokeColor: '#FF0000',
          strokeWeight: 2,
          editable: false,
          map: that.map,
        });
        this.polylines.push(polyline)
      },
      changeData: function (page) {
        this.currentPage = page
        this.loadData(page)
      },
      showEditDialog: function (row, index) {
        this.fullscreenLoading = false
        this.dialogEditFormVisible = true
        this.curEditForm.title = row.title
        this.curEditForm.desc = row.desc
        let startTime = new Date()
        startTime.setTime(row.timestamp)
        this.curEditForm.time = startTime
      },
      submitEditForm: function () {
        let that = this
        console.log(this.curEditForm.time.getTime())
        this.fullscreenLoading = true
        setTimeout(() => { that.fullscreenLoading = false }, 2000)
      },
      closeMap: function () {
        this.showMap = false
      },
      initMap: function () {
        let that = this
        TMap('BH3BZ-OWLW6-6KNSQ-MHGH5-ABJHZ-4KFW6').then(qq => {
          that.qq = qq
          that.center = new qq.maps.LatLng(40.01945601727397, 116.46899342536926)
          that.map = new qq.maps.Map(document.getElementById('qqmap'), {
            // 地图的中心地理坐标。
            center: that.center,
            zoom: parseInt(15),
            disableDefaultUI: true
          })
          that.geocoder = new qq.maps.Geocoder()
          function CloseController(controllDiv, map) {
            controllDiv.style.padding = '5px'
            controllDiv.style.backgroundColor = '#ffffff'
            controllDiv.style.cursor = 'pointer'
            controllDiv.innerHTML = '关闭地图'
            controllDiv.addEventListener('click', function () {
              that.showMap = false
              that.clearCurrentMarket()
            }, false)
          }
          let customZoomDiv = document.createElement('div')
          // 关闭地图按钮
          that.customZoomControl = new CloseController(customZoomDiv, that.map)
          // 将控件添加到controls栈变量并将其设置在顶部位置
          that.map.controls[qq.maps.ControlPosition.TOP_RIGHT].push(customZoomDiv)
          // 调用Poi检索类
          that.searchService = new that.qq.maps.SearchService({
            map: that.map
          })
        })
      },
      addMarker: function (lat, lng, address, isCheck) {
        let that = this
        var center = new qq.maps.LatLng(lat, lng);
        var anchor = new qq.maps.Point(6, 6),
          size = new qq.maps.Size(24, 24),
          origin = new qq.maps.Point(0, 0),
          icon = new qq.maps.MarkerImage('https://lbs.qq.com/javascript_v2/img/center.gif', size, origin, anchor);
        var marker = new qq.maps.Marker({
          icon: icon,
          position: center,
          animation: qq.maps.MarkerAnimation.DROP,
          map: that.map
        });
        let color = isCheck ? new qq.maps.Color(0, 191, 255, 0.6) : new qq.maps.Color(0, 0, 0, 0.4)
        var circle = new qq.maps.Circle({
          map: that.map,
          center: center,
          radius: 500,
          fillColor: color,
          strokeWeight: 0
        });
        var label = new qq.maps.Label({
          position: center,
          map: that.map,
          content: address
        });
        that.circles.push(circle)
        that.markers.push(marker)
        that.labels.push(label)
      },
      //清除覆盖物
      clearOverlays: function (overlays) {
        var overlay;
        while (overlay = overlays.pop()) {
          overlay.setMap(null);
        }
      },
      taskInfo() {
        this.clearOverlays(this.circles)
        this.clearOverlays(this.labels)
        this.clearOverlays(this.markers)
        this.clearOverlays(this.polylines)
        this.map.panTo(new qq.maps.LatLng(this.deviceData[0].latitude, this.deviceData[0].longitude));
        this.showMap = true;
        for (let i of this.deviceData) {
          this.addMarker(i.latitude, i.longitude, i.address, i.isCheck)
        }
      },
      clearCurrentMarket: function () {

      },
      setDeviceMap: function (latLng) {
        let that = this
        // 设置服务请求成功的回调函数
        this.geocoder.setComplete(function (r) {
          let adr = r.detail.addressComponents
          // console.log(adr)
          if (adr.province === '北京市' || adr.province === '上海市') {
            adr.province = ''
          }
          let address = adr.province + adr.city + adr.district + adr.street + adr.streetNumber + adr.town
          // console.log(address)
          that.$axios.get(that.APIURL + '/device/setMap', { params: { id: that.deviceData[that.currentIndex].id, lat: latLng.lat, lng: latLng.lng, address: address } }).then(function (response) {
            if (response !== false) {
              that.deviceData[that.currentIndex].latitude = latLng.lat
              that.deviceData[that.currentIndex].longitude = latLng.lng
              that.deviceData[that.currentIndex].address = address
              that.$set(that.deviceData, that.currentIndex, that.deviceData[that.currentIndex])
              that.$message({ type: 'success', message: '位置更新成功!' })
            }
          })
        })
        // 对指定地址进行解析
        this.geocoder.getAddress(latLng)
      },
      searchAddress: function () {
        if (!this.address) {
          this.$message({ type: 'error', message: '请输入地址!' })
        }
        if (!this.cityValue || this.cityValue === '请选择') {
          this.$message({ type: 'error', message: '请选择区域!' })
        }
        this.searchService.setLocation(this.cityValue)
        this.searchService.search(this.address)
      }
    },
    mounted: function () {
      this.initMap()
      this.loadData()
    }
  }
</script>

<style scoped>
  .tableToolsbar {
    margin-bottom: 10px;
  }

  .transition-box {
    margin-bottom: 10px;
    width: 200px;
    height: 100px;
    border-radius: 4px;
    background-color: #409EFF;
    text-align: center;
    color: #fff;
    padding: 40px 20px;
    box-sizing: border-box;
    margin-right: 20px;
  }

  .dialogAddTast {
    display: flex;
  }

  .dialogAddTast .left,
  .dialogAddTast .right {
    width: 50%;
  }

  .dialogAddTast .left {
    padding-right: 5px;
  }

  .dialogAddTast .right {
    padding-left: 5px;
  }

  .dialogAddTast .right .label,
  .dialogAddTast .left .label {
    border-left: 2px #409EFF solid;
    padding-left: 5px;
    box-sizing: border-box;
  }

  .dialogAddTast .right .device {
    min-height: 30%
  }

  .dialogAddTast .left span,
  .dialogAddTast .right span {
    margin-right: 10px;
    margin-top: 10px;
  }

  .peopleInfo {
    width: 250px;
    height: 90%;
    position: absolute;
    top: 75px;
    left: 20px;
  }

  .peopleInfo ul {
    padding: 0;
    height: 45%;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 5px;
  }

  .peopleInfo ul li {
    list-style: none;
    height: 40px;
    border-bottom: 1px solid #eeeeee;
    font-size: 14px;
    margin-bottom: 5px;
    padding-bottom: 5px;
    display: flex;
    color: #fff;
  }
  .peopleInfo ul .item .address,
  .peopleInfo ul .item .wxNum {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 40px;
    padding: 0 5px 0 0;
    color: #fff;
    text-align: center;
  }

  .peopleInfo ul .item .updated_at {
    width: 100px;
    display: flex;
    color: #fff;
    justify-content: center;
    align-items: center;
  }
</style>